package com.zwj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwj.bo.AuthBo;
import com.zwj.dto.Result;
import com.zwj.dto.User;
import com.zwj.entity.SysUserEntity;
import com.zwj.enums.IsDeletedEnum;
import com.zwj.enums.StatusEnum;
import com.zwj.mapper.SysUserMapper;
import com.zwj.service.AuthService;
import com.zwj.utils.DataCheckUtils;
import com.zwj.utils.TokenUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;

@Service
public class AuthServiceImpl implements AuthService {
    private final SysUserMapper sysUserMapper;
    public AuthServiceImpl(SysUserMapper sysUserMapper) {
        this.sysUserMapper = sysUserMapper;
    }

    @Override
    public Result login(AuthBo authBo) {
        //数据校验
        DataCheckUtils.isNotBlank(authBo.getAccount(), "用户账号不能为空!");
        DataCheckUtils.isNotBlank(authBo.getPassword(), "密码不能为空!");
//        DataCheckUtils.isNotBlank(userLoginBo.getCode(), "验证码不能为空!");
        //以用户类型与账号查询用户信息
        QueryWrapper<SysUserEntity> sectionQueryWrapper = new QueryWrapper<>();
        sectionQueryWrapper.lambda().eq(SysUserEntity::getAccount, authBo.getAccount()).eq(SysUserEntity::getIsDeleted, IsDeletedEnum.NO.getKey())
                .select(SysUserEntity::getStatus,SysUserEntity::getPassword,SysUserEntity::getId,SysUserEntity::getName);
        SysUserEntity user = sysUserMapper.selectOne(sectionQueryWrapper);
        //查询结果校验
        if (user == null) {
            return Result.error().message("账号不存在！");
        }
        if (StatusEnum.INVALID.getKey().equals(user.getStatus())) {
            return Result.error().message("用户已停用！");
        }
        //md5加密
        if(!user.getPassword().equals(DigestUtils.md5DigestAsHex(authBo.getPassword().getBytes(StandardCharsets.UTF_8)))){
            return Result.error().message("用户密码错误！");
        }
        //生成token
        String token = TokenUtils.getJwtToken(user.getId().toString());

        return Result.ok().data(new User(token,user.getName()));
    }
}
